import { NextRequest, NextResponse } from 'next/server'
import axios from 'axios'
import OpenAI from 'openai'

// API配置
const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1'
const DEEPSEEK_API_KEY = 'sk-877b9e57cdbc4f7ebb617c564a25e0b0'
const BAIDU_API_KEY = 'z5eRLAp2JlcjbjVyCcUUTjaz'
const BAIDU_SECRET_KEY = 's8MEDSoj2B8qNwdeWua9uahJRH7MnZz7'
const OPENAI_API_KEY ='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'

// 创建OpenAI客户端实例
const openai = new OpenAI({
  apiKey: OPENAI_API_KEY,
})

// 主题映射
const themeMapping = {
  friendship: '友谊与分享',
  courage: '勇气与冒险',
  kindness: '善良与爱心',
  learning: '学习与成长',
  nature: '自然与环保',
  family: '家庭与亲情',
}

const ageGroupMapping = {
  '3-5': '使用简单词汇和重复句式，适合3-5岁儿童',
  '6-8': '使用基础词汇和完整句子，适合6-8岁儿童',
  '9-12': '使用丰富词汇和复杂情节，适合9-12岁儿童',
}

const lengthMapping = {
  short: '约100-150词',
  medium: '约200-300词',
  long: '约400-500词',
}

interface ComicPanel {
  id: string
  imageUrl: string
  caption: string
  englishCaption: string
  order: number
}

// 获取百度AI访问令牌
async function getBaiduAccessToken(): Promise<string | null> {
  try {
    console.log('正在获取百度AI访问令牌...')
    const authUrl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${BAIDU_API_KEY}&client_secret=${BAIDU_SECRET_KEY}`
    console.log('认证URL:', authUrl)
    
    const response = await axios.get(authUrl)
    console.log('百度认证响应:', response.data)
    
    if (response.data.access_token) {
      console.log('成功获取访问令牌')
      return response.data.access_token
    } else {
      console.error('未获取到访问令牌:', response.data)
      return null
    }
  } catch (error: any) {
    console.error('获取百度AI访问令牌失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
    }
    return null
  }
}

// 使用百度文心一格生成图片
async function generateBaiduImage(prompt: string): Promise<string | null> {
  const maxRetries = 3
  const retryDelay = 1000 // 1秒延迟，适应QPS=2的限制

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      console.log(`开始使用百度文心一格生成图片... (尝试 ${attempt}/${maxRetries})`)
      console.log('提示词:', prompt)
      
      const accessToken = await getBaiduAccessToken()
      if (!accessToken) {
        console.error('无法获取访问令牌，跳过百度API')
        return null
      }

      // 使用百度文心一格API端点
      const generateUrl = `https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2imgv2?access_token=${accessToken}`
      console.log('生成图片URL:', generateUrl)
      
      const requestBody = {
        prompt: prompt,
        height: 1024,
        width: 1024,
        n: 1,
      }
      console.log('请求体:', requestBody)
      
      const response = await axios.post(generateUrl, requestBody, {
        headers: {
          'Content-Type': 'application/json',
        },
      })
      
      console.log('百度API响应:', response.data)

             // 检查是否返回了任务ID（异步模式）
       if (response.data.data && response.data.data.primary_task_id) {
         const taskId = response.data.data.primary_task_id
         console.log('获取到任务ID:', taskId)
         console.log('✅ 图片生成任务已提交，但由于下载API问题，使用占位符图片')
         
         // 由于百度API下载功能有问题，直接返回占位符图片
         // 在实际应用中，可以考虑使用其他AI图片生成服务
         return null
       } else if (response.data.data && response.data.data[0] && response.data.data[0].image) {
         // 同步返回图片数据
         const base64Image = response.data.data[0].image
         console.log('成功生成图片，Base64长度:', base64Image.length)
         return `data:image/png;base64,${base64Image}`
       } else {
         console.error('API响应中没有图片数据或task_id:', response.data)
         return null
       }
    } catch (error: any) {
      console.error(`百度文心一格图片生成失败 (尝试 ${attempt}/${maxRetries}):`, error)
      
      if (error.response) {
        console.error('错误响应:', error.response.data)
        
        // 检查是否是QPS限制错误
        if (error.response.data.error_code === 18) {
          console.log(`QPS限制触发 (QPS=2)，等待 ${retryDelay}ms 后重试...`)
          if (attempt < maxRetries) {
            await new Promise(resolve => setTimeout(resolve, retryDelay))
            // 继续下一次循环
            continue
          } else {
            console.log('已达到最大重试次数，使用占位符图片')
            return null
          }
        }
      }
      
      // 如果不是QPS限制错误，直接返回null
      console.log('非QPS限制错误，直接返回null')
      return null
    }
  }
  
  return null
}

/**
 * 使用OpenAI DALL-E生成插图
 * @param prompt 图片生成提示词
 * @param theme 故事主题
 * @param ageGroup 目标年龄组
 * @returns 生成的图片URL或null
 */
async function generateOpenAIIllustration(prompt: string, theme: string, ageGroup: string): Promise<string | null> {
  try {
    // 检查OpenAI API密钥
    if (!OPENAI_API_KEY || OPENAI_API_KEY === 'your-openai-api-key-here') {
      console.warn('OpenAI API密钥未配置，跳过OpenAI插图生成')
      return null
    }

    console.log('开始使用OpenAI DALL-E生成插图...')
    console.log('提示词:', prompt)

    const response = await openai.images.generate({
      model: 'dall-e-3', // 使用DALL-E 3模型，质量更高
      prompt: prompt,
      n: 1, // 生成1张图片
      size: '1024x1024', // 1024x1024像素
      quality: 'standard', // 标准质量
      style: 'vivid', // 生动风格，适合儿童绘本
    })

    console.log('OpenAI API响应:', response)

    if (response.data && response.data[0] && response.data[0].url) {
      const imageUrl = response.data[0].url
      console.log('成功生成OpenAI插图，URL:', imageUrl)
      return imageUrl
    } else {
      console.error('OpenAI API响应中没有图片URL:', response)
      return null
    }
  } catch (error: any) {
    console.error('OpenAI插图生成失败:', error)
    
    if (error.response) {
      console.error('错误响应:', error.response.data)
    }
    
    return null
  }
}

/**
 * 生成适合儿童绘本的插图提示词
 * @param theme 故事主题
 * @param ageGroup 目标年龄组
 * @param storyContent 故事内容摘要
 * @param illustrationType 插图类型
 * @returns 优化的提示词
 */
function generateIllustrationPrompt(
  theme: string,
  ageGroup: string,
  storyContent: string,
  illustrationType: 'main' | 'comic' = 'main'
): string {
  const themeName = themeMapping[theme as keyof typeof themeMapping] || theme
  const ageDescription = ageGroupMapping[ageGroup as keyof typeof ageGroupMapping] || ageGroup
  
  // 根据插图类型生成不同的提示词
  if (illustrationType === 'main') {
    // 主插图：水彩风格，温暖明亮
    return `Create a beautiful watercolor illustration for a children's picture book. 
    Theme: ${themeName} (${theme})
    Target age: ${ageDescription}
    Style: Soft watercolor painting with warm, bright colors
    Content: ${storyContent.substring(0, 200)}...
    Requirements:
    - Whimsical and child-friendly art style
    - Soft, dreamy watercolor technique
    - Warm and inviting color palette
    - Cute, expressive characters
    - Safe and positive imagery
    - High quality, professional children's book illustration
    - No text or words in the image
    - Suitable for ${ageGroup} year old children`
  } else {
    // 漫画插图：卡通风格，生动有趣
    return `Create a vibrant cartoon illustration for a children's comic panel. 
    Theme: ${themeName} (${theme})
    Target age: ${ageDescription}
    Style: Colorful cartoon with bold, clean lines
    Content: ${storyContent.substring(0, 150)}...
    Requirements:
    - Bright, energetic cartoon style
    - Bold, clean line work
    - Vibrant, saturated colors
    - Expressive, cute characters
    - Dynamic composition
    - Child-safe content
    - Comic panel format
    - No text or speech bubbles
    - Suitable for ${ageGroup} year old children`
  }
}

// 从故事内容中提取关键词用于图片搜索
function extractKeywords(storyContent: string, ageGroup: string): string[] {
  // 根据年龄组调整关键词
  const ageKeywords = {
    '3-5': ['cute', 'colorful', 'simple', 'friendly'],
    '6-8': ['fun', 'adventure', 'bright', 'playful'],
    '9-12': ['exciting', 'mysterious', 'vibrant', 'dynamic']
  }

  // 从故事内容中提取主题关键词
  const commonThemes = [
    'animal', 'forest', 'castle', 'princess', 'dragon', 'space', 'ocean',
    'mountain', 'river', 'tree', 'flower', 'sun', 'moon', 'star',
    'house', 'car', 'train', 'plane', 'boat', 'bike', 'ball',
    'book', 'school', 'park', 'garden', 'beach', 'snow', 'rain'
  ]

  const extractedKeywords: string[] = []
  
  // 检查故事内容中的主题词
  commonThemes.forEach(theme => {
    if (storyContent.toLowerCase().includes(theme)) {
      extractedKeywords.push(theme)
    }
  })

  // 添加年龄组相关关键词
  const ageSpecificKeywords = ageKeywords[ageGroup as keyof typeof ageKeywords] || []
  extractedKeywords.push(...ageSpecificKeywords)

  // 如果没有找到关键词，使用默认关键词
  if (extractedKeywords.length === 0) {
    extractedKeywords.push('children', 'story', 'illustration')
  }

  return extractedKeywords.slice(0, 3) // 限制关键词数量
}

// 从Unsplash搜索图片
async function searchUnsplashImages(query: string, count: number = 1) {
  try {
    // 注意：这里需要配置Unsplash API密钥
    // 为了演示，我们使用一个公开的Unsplash图片
    const defaultImages = [
      'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=600&fit=crop',
      'https://images.unsplash.com/photo-1518791841217-8f162f1e1131?w=800&h=600&fit=crop',
      'https://images.unsplash.com/photo-1543852786-1cf6624b9983?w=800&h=600&fit=crop',
      'https://images.unsplash.com/photo-1558618666-fcd25c85cd64?w=800&h=600&fit=crop'
    ]
    
    const randomIndex = Math.floor(Math.random() * defaultImages.length)
    return [{
      url: defaultImages[randomIndex],
      thumb: defaultImages[randomIndex].replace('w=800&h=600', 'w=400&h=300'),
      alt: query,
      photographer: 'Unsplash',
      photographerUrl: 'https://unsplash.com',
      source: 'Unsplash'
    }]
  } catch (error) {
    console.error('图片搜索错误:', error)
    return []
  }
}

// 生成图片（优先使用图片搜索，其次AI生成，最后占位符）
async function generateImage(prompt: string, theme: string, ageGroup: string, storyContent: string) {
  try {
    // 1. 优先尝试图片搜索
    const keywords = extractKeywords(storyContent, ageGroup)
    const searchQuery = `${keywords.join(' ')} ${theme} children story`
    const searchResults = await searchUnsplashImages(searchQuery, 1)
    
    if (searchResults.length > 0) {
      console.log('使用搜索到的图片')
      return searchResults[0].url
    }

    // 2. 备选方案：OpenAI DALL-E
    const openAIPrompt = generateIllustrationPrompt(theme, ageGroup, storyContent, 'main')
    const openAIImage = await generateOpenAIIllustration(openAIPrompt, theme, ageGroup)
    if (openAIImage) {
      console.log('使用OpenAI生成的插图')
      return openAIImage
    }

    // 3. 备选方案：百度文心一格
    const baiduImage = await generateBaiduImage(prompt)
    if (baiduImage) {
      console.log('使用百度文心一格生成的插图')
      return baiduImage
    }

    // 4. 最后备选：占位符图片
    const colors = ['#FFB6C1', '#87CEEB', '#98FB98', '#DDA0DD', '#F0E68C']
    const randomColor = colors[Math.floor(Math.random() * colors.length)]
    console.log('使用占位符插图')
    return `https://via.placeholder.com/1024x1024/${randomColor.replace('#', '')}/FFFFFF?text=Story+Illustration`
  } catch (error) {
    console.error('图片生成失败:', error)
    return 'https://via.placeholder.com/1024x1024/87CEEB/FFFFFF?text=Story+Illustration'
  }
}

// 生成文本
async function generateText(prompt: string) {
  try {
    const response = await axios.post(
      `${DEEPSEEK_API_URL}/chat/completions`,
      {
        model: 'deepseek-chat',
        messages: [
          { role: 'system', content: '你是一个专业的儿童文学作家，擅长创作阳光积极的英语绘本故事。' },
          { role: 'user', content: prompt }
        ],
        temperature: 0.8,
        max_tokens: 2000,
      },
      {
        headers: {
          'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,
          'Content-Type': 'application/json',
        },
      }
    )
    return response.data.choices[0]?.message?.content
  } catch (error) {
    console.error('DeepSeek API调用失败:', error)
    return null
  }
}

// 生成卡通漫画面板
async function generateComicPanels(storyContent: string, theme: string, ageGroup: string): Promise<ComicPanel[]> {
  try {
    const paragraphs = storyContent.split('\n\n').filter(p => p.trim())
    const comicPanels: ComicPanel[] = []
    
<<<<<<< HEAD
    // 只生成1张AI图片，适应API限制
    const maxImages = 1
=======
    // 限制最多生成2张AI图片，适应API限制
    const maxImages = 2
>>>>>>> b956327bebcaf4d8b1502b4d365032359646e684
    const imageCount = Math.min(paragraphs.length, maxImages)
    
    for (let i = 0; i < imageCount; i++) {
      const paragraph = paragraphs[i]
<<<<<<< HEAD
      const comicPrompt = `卡通风格，${themeMapping[theme as keyof typeof themeMapping]}主题，漫画插图，描绘：${paragraph.substring(0, 100)}...，适合${ageGroup}岁儿童，明亮色彩，可爱角色`
=======
      
      // 添加延迟以避免API限制，每个图片生成间隔1秒
      if (i > 0) {
        console.log(`等待1秒后生成第${i + 1}张漫画图片...`)
        await new Promise(resolve => setTimeout(resolve, 1000))
      }
>>>>>>> b956327bebcaf4d8b1502b4d365032359646e684
      
      // 使用OpenAI生成漫画插图
      const comicPrompt = generateIllustrationPrompt(theme, ageGroup, paragraph, 'comic')
      const imageUrl = await generateImage(comicPrompt, theme, ageGroup, paragraph)
      
      if (imageUrl) {
        comicPanels.push({
          id: `panel-${i + 1}`,
          imageUrl,
          caption: paragraph.substring(0, 80) + (paragraph.length > 80 ? '...' : ''),
          englishCaption: `Comic: ${paragraph.substring(0, 60)}...`,
          order: i + 1,
        })
      }
    }
    
    console.log(`成功生成 ${comicPanels.length} 张AI图片（最多${maxImages}张）`)
    return comicPanels
  } catch (error) {
    console.error('生成卡通漫画失败:', error)
    return []
  }
}

export async function POST(request: NextRequest) {
  try {
    const { theme, ageGroup, storyLength, imageType = 'main' } = await request.json()

    if (!theme || !ageGroup || !storyLength) {
      return NextResponse.json({ error: '缺少必要参数' }, { status: 400 })
    }

    if (!DEEPSEEK_API_KEY) {
      return NextResponse.json({ error: 'DeepSeek API密钥未配置' }, { status: 500 })
    }

    const storyPrompt = `请创作一个阳光积极、充满正能量的英语绘本小故事。

要求：
1. 主题：${themeMapping[theme as keyof typeof themeMapping]}
2. 目标年龄：${ageGroupMapping[ageGroup as keyof typeof ageGroupMapping]}
3. 故事长度：${lengthMapping[storyLength as keyof typeof lengthMapping]}
4. 故事风格：温暖、积极、富有教育意义
5. 语言要求：英文表达优美、简单易懂，适合儿童阅读
6. 结构要求：请将故事分成3-4个段落，每个段落用双换行符分隔，便于生成漫画面板

请按以下JSON格式返回：
{
  "title": "中文标题",
  "englishTitle": "English Title",
  "content": "中文故事内容（包含段落分隔）",
  "englishContent": "English story content (with paragraph breaks)",
  "moral": "中文故事寓意",
  "englishMoral": "English story moral",
  "vocabulary": ["中文关键词1", "中文关键词2", "中文关键词3"],
  "englishVocabulary": ["English word 1", "English word 2", "English word 3"]
}`

    const storyContent = await generateText(storyPrompt)
    if (!storyContent) {
      throw new Error('故事生成失败')
    }

    let storyData
    try {
      storyData = JSON.parse(storyContent)
    } catch (error) {
      storyData = generateFallbackStory(theme, ageGroup, storyLength)
    }

<<<<<<< HEAD
    let mainImageUrl = null
    let comicPanels: ComicPanel[] = []
    
    // 根据imageType参数决定生成哪种图片
    if (imageType === 'main') {
      // 生成主插图
      const mainImagePrompt = `水彩风格，${themeMapping[theme as keyof typeof themeMapping]}主题，适合${ageGroup}岁儿童的绘本插图，温暖积极，明亮色彩，可爱角色`
      mainImageUrl = await generateImage(mainImagePrompt)
      console.log('生成主插图完成')
    } else if (imageType === 'comic') {
      // 生成漫画插图
=======
    const mainImagePrompt = `水彩风格，${themeMapping[theme as keyof typeof themeMapping]}主题，适合${ageGroup}岁儿童的绘本插图，温暖积极，明亮色彩，可爱角色`
    const mainImageUrl = await generateImage(mainImagePrompt, theme, ageGroup, storyData.content)

    let comicPanels: ComicPanel[] = []
    if (includeComics) {
      // 在主插图和漫画生成之间添加延迟，避免API限制
      console.log('主插图生成完成，等待1秒后开始生成漫画...')
      await new Promise(resolve => setTimeout(resolve, 1000))
>>>>>>> b956327bebcaf4d8b1502b4d365032359646e684
      comicPanels = await generateComicPanels(storyData.content, theme, ageGroup)
      console.log('生成漫画插图完成')
    }
    
    // 记录AI图片数量
    const totalImages = (mainImageUrl ? 1 : 0) + comicPanels.length
    console.log(`总共生成 ${totalImages} 张AI图片`)

    const fullStoryData = {
      ...storyData,
      illustration: mainImageUrl,
      comicPanels: comicPanels.length > 0 ? comicPanels : undefined,
      theme,
      ageGroup,
      storyLength,
    }

    return NextResponse.json(fullStoryData)

  } catch (error) {
    console.error('生成故事时出错:', error)
    return NextResponse.json({ error: '生成故事失败，请稍后重试' }, { status: 500 })
  }
}

function generateFallbackStory(theme: string, ageGroup: string, storyLength: string) {
  const fallbackStories = {
    friendship: {
      title: '小兔子的友谊',
      englishTitle: 'Little Rabbit\'s Friendship',
      content: '从前有一只小兔子，它非常喜欢交朋友。\n\n有一天，它在森林里遇到了一只受伤的小鸟。小兔子立刻跑过去帮助小鸟，给它找来食物和水。\n\n小鸟很快就康复了，它们成为了最好的朋友。从那以后，小兔子和小鸟总是在一起玩耍，分享快乐和困难。\n\n它们的故事告诉我们，真正的友谊是互相帮助和关心。',
      englishContent: 'Once upon a time, there was a little rabbit who loved making friends.\n\nOne day, it met an injured bird in the forest. The little rabbit immediately ran to help the bird, bringing it food and water.\n\nThe bird recovered quickly, and they became the best of friends. From then on, the little rabbit and the bird always played together, sharing joy and difficulties.\n\nTheir story teaches us that true friendship is about helping and caring for each other.',
      moral: '友谊需要互相帮助和关心，真正的朋友会在困难时伸出援手。',
      englishMoral: 'Friendship requires mutual help and care. True friends lend a hand in times of difficulty.',
      vocabulary: ['友谊', '帮助', '关心', '朋友'],
      englishVocabulary: ['friendship', 'help', 'care', 'friend'],
    },
    courage: {
      title: '勇敢的小熊',
      englishTitle: 'The Brave Little Bear',
      content: '小熊一直害怕黑暗，不敢一个人睡觉。\n\n妈妈告诉它，勇敢不是不害怕，而是面对害怕的勇气。一天晚上，小熊决定要勇敢起来。\n\n它深吸一口气，关上了灯。虽然心里还是有点害怕，但它坚持了下来。\n\n渐渐地，小熊发现黑暗并不可怕。它学会了勇敢面对自己的恐惧，成为了一个真正勇敢的小熊。',
      englishContent: 'Little Bear was always afraid of the dark and didn\'t dare to sleep alone.\n\nMom told it that being brave doesn\'t mean not being afraid, but having the courage to face fear. One night, Little Bear decided to be brave.\n\nIt took a deep breath and turned off the light. Although it was still a bit scared, it persevered.\n\nGradually, Little Bear found that darkness wasn\'t scary. It learned to bravely face its fears and became a truly brave little bear.',
      moral: '勇敢不是不害怕，而是有勇气面对害怕。',
      englishMoral: 'Being brave doesn\'t mean not being afraid, but having the courage to face fear.',
      vocabulary: ['勇敢', '害怕', '勇气', '面对'],
      englishVocabulary: ['brave', 'afraid', 'courage', 'face'],
    },
  }

  return fallbackStories[theme as keyof typeof fallbackStories] || fallbackStories.friendship
} 